//
//  YAYIPhotoGroupsController.m
//  图片多选
//
//  Created by hxp on 16/6/27.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIPhotoGroupsController.h"
#import<AssetsLibrary/AssetsLibrary.h>
#import "YAYIPhotoItemController.h"
@interface YAYIPhotoGroupsController ()<YAYIPhotoItemControllerDelegate>
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)ALAssetsLibrary *assetsLibrary;
@property (nonatomic,strong)UIButton *backBtn;
@end

@implementation YAYIPhotoGroupsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"相册";
    self.tableView.tableFooterView = [UIView new];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage imageNamed:@"navagation_icon"] stretchableImageWithLeftCapWidth:5 topCapHeight:8] forBarMetrics:UIBarMetricsDefault];
    [self getDataSource];
    [self getPhotoGroups];
    [self createBackButton];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    
    return self.dataSource.count;
}
-(void)getDataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    
}

-(void)getPhotoGroups{
    if (!_assetsLibrary) {
        _assetsLibrary = [[ALAssetsLibrary alloc]init];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [_assetsLibrary  enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
            if(group){
                [self.dataSource addObject:group];
                //[self performSelectorOnMainThread:@selector(reloadTableView) withObject:nil waitUntilDone:YES];
                [self.tableView reloadData];
            }
        } failureBlock:^(NSError *error) {
            YAYILog(@"Group not found!\n");
        }];
    });
}
-(void)reloadTableView{
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"AlbumGroupCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    //获取相册图片数
    ALAssetsGroup *group = (ALAssetsGroup*)[self.dataSource objectAtIndex:indexPath.row];
    [group setAssetsFilter:[ALAssetsFilter allPhotos]];
    NSInteger groupCount = [group numberOfAssets];
    
    //相册来源
    NSString *groupName = [group valueForProperty:ALAssetsGroupPropertyName];
    if ([groupName isEqualToString:@"Camera Roll"]) {
        groupName = @"相机胶卷";
    } else if ([groupName isEqualToString:@"My Photo Stream"]) {
        groupName = @"我的照片流";
    }
    
    //cell.textLabel.
    //显示图片张数
    UIImageView *imageView = [UIImageView new];
    [cell.contentView addSubview:imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.centerY.mas_equalTo(cell.contentView);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    [imageView setImage:[UIImage imageWithCGImage:[(ALAssetsGroup*)[self.dataSource objectAtIndex:indexPath.row] posterImage]]];
    //显示第一张图片
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    UILabel *label = [UILabel new];
    [cell.contentView addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(imageView.mas_right).with.offset(20);
        make.centerY.mas_equalTo(imageView.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(190, 20));
    }];
    label.text = [NSString stringWithFormat:@"%@ (%ld)",groupName, groupCount];
    //显示cell右侧小箭头
    
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YAYIPhotoItemController *colleView = [YAYIPhotoItemController new];
    colleView.selectedAssetsGroup = self.dataSource[indexPath.row];
    colleView.delegate = self;
    [self.navigationController pushViewController:colleView animated:YES];

}
-(void)imageAry:(NSArray *)images
{
    if (_delagate && [_delagate respondsToSelector:@selector(imageAry:)]) {
        [_delagate imageAry:images];
    }
}
/** 创建返回按钮
 *
 */
-(void)createBackButton{
    if (self.backBtn == nil) {
        
        self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.backBtn setImage:[UIImage  imageNamed:@"back_button"] forState:UIControlStateNormal];
        self.backBtn.frame = CGRectMake(0, 0, 70, 20);
        self.backBtn.contentMode = UIViewContentModeLeft;
        self.backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *item = [[UIBarButtonItem  alloc] initWithCustomView:self.backBtn];
        self.navigationItem.leftBarButtonItem = item;
    }
}
-(void)backAction:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
